package cn.iocoder.yudao.module.project.controller.admin.defectiveproductrecord;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.project.dal.dataobject.internalcode.InternalCodeDO;
import cn.iocoder.yudao.module.project.dal.dataobject.internalworkstationplan.InternalWorkstationPlanDO;
import cn.iocoder.yudao.module.project.dal.dataobject.orderdetail.OrderDetailDO;
import cn.iocoder.yudao.module.project.dal.dataobject.productioncode.ProductionCodeDO;
import cn.iocoder.yudao.module.project.dal.mysql.internalworkstationplan.InternalWorkstationPlanMapper;
import cn.iocoder.yudao.module.project.service.internalcode.InternalCodeService;
import cn.iocoder.yudao.module.project.service.internalworkstationplan.InternalWorkstationPlanService;
import cn.iocoder.yudao.module.project.service.orderdetail.OrderDetailService;
import cn.iocoder.yudao.module.project.service.productioncode.ProductionCodeService;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.module.project.config.projectDefine.HTTP_STATUS.ERROR_STATUS;

import cn.iocoder.yudao.module.project.controller.admin.defectiveproductrecord.vo.*;
import cn.iocoder.yudao.module.project.dal.dataobject.defectiveproductrecord.DefectiveProductRecordDO;
import cn.iocoder.yudao.module.project.service.defectiveproductrecord.DefectiveProductRecordService;

@Tag(name = "管理后台 - 不良品记录")
@RestController
@RequestMapping("/project/defective-product-record")
@Validated
public class DefectiveProductRecordController {

    @Resource
    private DefectiveProductRecordService defectiveProductRecordService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private ProductionCodeService productionCodeService;

    @Resource
    private InternalCodeService internalCodeService;

    @Resource
    private OrderDetailService orderDetailService;

    @Resource
    private DictDataApi dictDataApi;

    @Resource
    private InternalWorkstationPlanMapper internalWorkstationPlanMapper;

    /*@PostMapping("/create")
    @Operation(summary = "创建不良品记录")
    //@PreAuthorize("@ss.hasPermission('project:defective-product-record:create')")
    public CommonResult<String> createDefectiveProductRecord(@Valid @RequestBody DefectiveProductRecordSaveReqVO createReqVO) {
        return success(defectiveProductRecordService.createDefectiveProductRecord(createReqVO));
    }*/

    @PutMapping("/update")
    @Operation(summary = "更新不良品记录")
    //@PreAuthorize("@ss.hasPermission('project:defective-product-record:update')")
    public CommonResult<Boolean> updateDefectiveProductRecord(@Valid @RequestBody DefectiveProductRecordSaveReqVO updateReqVO) {
        defectiveProductRecordService.updateDefectiveProductRecord(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除不良品记录")
    @Parameter(name = "id", description = "编号", required = true)
    //@PreAuthorize("@ss.hasPermission('project:defective-product-record:delete')")
    public CommonResult<Boolean> deleteDefectiveProductRecord(@RequestParam("id") String id) {
        defectiveProductRecordService.deleteDefectiveProductRecord(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得不良品记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    //@PreAuthorize("@ss.hasPermission('project:defective-product-record:query')")
    public CommonResult<DefectiveProductRecordRespVO> getDefectiveProductRecord(@RequestParam("id") String id) {
        DefectiveProductRecordDO defectiveProductRecord = defectiveProductRecordService.getDefectiveProductRecord(id);
        return success(BeanUtils.toBean(defectiveProductRecord, DefectiveProductRecordRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得不良品记录分页")
    //@PreAuthorize("@ss.hasPermission('project:defective-product-record:query')")
    public CommonResult<PageResult<DefectiveProductRecordRespVO>> getDefectiveProductRecordPage(@Valid DefectiveProductRecordPageReqVO pageReqVO) {
        PageResult<DefectiveProductRecordDO> pageResult = defectiveProductRecordService.getDefectiveProductRecordPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DefectiveProductRecordRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出不良品记录 Excel")
    //@PreAuthorize("@ss.hasPermission('project:defective-product-record:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDefectiveProductRecordExcel(@Valid DefectiveProductRecordPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DefectiveProductRecordDO> list = defectiveProductRecordService.getDefectiveProductRecordPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "不良品记录.xls", "数据", DefectiveProductRecordRespVO.class,
                        BeanUtils.toBean(list, DefectiveProductRecordRespVO.class));
    }

    @PostMapping("/createDefectiveProductRecord")
    @Operation(summary = "创建不良品记录")
    public CommonResult<String> createDefectiveProductRecord(@Valid @RequestBody DefectiveProductRecordSaveReqVO createReqVO) {
        createReqVO.setOperatorTime(LocalDateTime.now());
        createReqVO.setId(UUID.randomUUID().toString());
        String username = adminUserApi.getUser(SecurityFrameworkUtils.getLoginUserId()).getUsername();
        createReqVO.setOperatorUser(username);

        InternalCodeDO internalCodeDO = internalCodeService.getInternalCode(createReqVO.getQueryCode());
        if(null == internalCodeDO){
            ProductionCodeDO productionCodeDO = productionCodeService.getProductionCode(createReqVO.getQueryCode());
            if(productionCodeDO == null){
                throw new ServiceException(ERROR_STATUS, "未查询到数据");
            }
            internalCodeDO = internalCodeService.getInternalCode(productionCodeDO.getInternalCode());
        }
        createReqVO.setInternalCode(internalCodeDO.getId());
        createReqVO.setOrderCode(internalCodeDO.getOrderCode());
        createReqVO.setOrderDetailId(internalCodeDO.getOrderDetailId());

        DefectiveProductRecordPageReqVO pageReqVO = new DefectiveProductRecordPageReqVO();
        pageReqVO.setInternalCode(internalCodeDO.getId());

        PageResult<DefectiveProductRecordDO> pageReqVOPageResult = defectiveProductRecordService.getDefectiveProductRecordPage(pageReqVO);
        if(pageReqVOPageResult.getTotal() > 0){
            throw new ServiceException(ERROR_STATUS, "内码数据已存在");
        }

        OrderDetailDO orderDetailDO = orderDetailService.getOrderDetail(internalCodeDO.getOrderDetailId());
        createReqVO.setFlex(orderDetailDO.getFlex());

        String defectiveItem = createReqVO.getDefectiveItem();
        DictDataRespDTO dictDataRespDTO = dictDataApi.getDictData("product_scrap_reason", defectiveItem);
        createReqVO.setDefectiveReason(dictDataRespDTO.getLabel());

        createReqVO.setId(UUID.randomUUID().toString());

        InternalWorkstationPlanDO internalWorkstationPlanDO = new InternalWorkstationPlanDO();
        internalWorkstationPlanDO.setCompletedStatus(0);
        internalWorkstationPlanMapper.update(internalWorkstationPlanDO, new QueryWrapper<InternalWorkstationPlanDO>().eq("internal_code", internalCodeDO.getId()));

        return success(defectiveProductRecordService.createDefectiveProductRecord(createReqVO));
    }

}